package com.tencent.cloud.iov.util;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;

/**
 * 线程工具类
 *
 * @author showxiao
 * @date 2018/10/11
 */
public final class ThreadUtils {

    private static volatile Handler sMainThreadHandler;

    private ThreadUtils() {}

    /**
     * 主线程执行任务
     *
     * @param runnable
     */
    public static void executeOnUiThread(final Runnable runnable) {
        executeOnUiThread(runnable, 0);
    }

    /**
     * 主线程执行任务
     *
     * @param runnable
     */
    public static void executeOnUiThread(final Runnable runnable, final long delayMillis) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            getMainThreadHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    runnable.run();
                }
            }, delayMillis);
        }
    }

    /**
     * 异步线程执行任务
     *
     * @param runnable
     */
    public static void executeOnIoThread(final Runnable runnable) {
        // XXX: 2018/10/11 @showxiao 可按需创建并维护独立线程池
        AsyncTask.THREAD_POOL_EXECUTOR.execute(runnable);
    }

    private static Handler getMainThreadHandler() {
        if (sMainThreadHandler == null) {
            synchronized (ThreadUtils.class) {
                if (sMainThreadHandler == null) {
                    sMainThreadHandler = new Handler(Looper.getMainLooper());
                }
            }
        }

        return sMainThreadHandler;
    }

}
